﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Genuilder.Extensibility
{
	public class ExtensionRepository
	{
		readonly object extendedObject;

		public ExtensionRepository(object extendedObject)
		{
			if(extendedObject == null)
			{
				throw new ArgumentNullException("extendedObject");
			}
			this.extendedObject = extendedObject;
		}

		readonly Dictionary<Type, object> extensions = new Dictionary<Type, object>();

		public T GetExtension<T>()
		{
			object extension;
			if(extensions.TryGetValue(typeof(T), out extension))
			{
				return (T)extension;
			}
			Exception innerException = null;
			//Try to create with the extended object as argument
			try
			{
				extension = Activator.CreateInstance(typeof(T), extendedObject);
			}
			catch(Exception ex)
			{
				innerException = ex;
			}
			if(extension != null)
			{
				extensions.Add(typeof(T), extension);
				return (T)extension;
			}
			//Try to create without constructor
			try
			{
				extension = Activator.CreateInstance<T>();
			}
			catch(Exception ex)
			{
				innerException = ex;
			}
			if(extension != null)
			{
				extensions.Add(typeof(T), extension);
				return (T)extension;
			}
			throw new InvalidOperationException(
				typeof(T).FullName
				+ " impossible to create with a parameterless constructor "
				+ "or with this extended object's type as parameter",
				innerException);
		}
	}
}
